from django.shortcuts import render,redirect,reverse
# Django自带的用户模型
from django.contrib.auth.models import User
# 自带验证、登录、登出函数
from django.contrib.auth import authenticate,login,logout

from utils.house_spider import ZufangSpider


# Create your views here.
def index(request):
    return render(request, 'index.html')


# 房源数据初始化
def houses_data_init(request):
    province = request.GET.get("p")
    if province:
        zf = ZufangSpider()
        zf.run(province)
        return render(request,'index.html')


# 地图视图
def map(request):
    return render(request,'map.html')

# 注册函数
def regist(request):
    username = request.POST.get('username')
    password1 = request.POST.get('pwd1')
    password2 = request.POST.get('pwd2')
    # print("*"*30)
    # print(username)
    # print(password1)
    # print(password2)
    if password1 != password2:
        return render(request,"index.html")
    else:

        user = User.objects.create_user(username=username,password=password1)
        user.password = password1
        login(request,user)
        return render(request,'index.html')


# 用户登录
def my_login(request):
    username = request.POST.get('username')
    pwd = request.POST.get("password")
    # print(username)
    # print(pwd)
    user = authenticate(request,username=username,password=pwd)
    # print(user)
    if user:
        login(request,user)
        return render(request,'index.html')
    else:
        return render(request,"index.html")


# 登出按钮
def my_logout(request):
    logout(request)
    return redirect(reverse('house:index'))


